package com.ruoyi.interview.aspect;

import com.ruoyi.interview.annotation.TLog;
import com.ruoyi.interview.domain.Log;
import com.ruoyi.interview.mapper.LogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetAddress;

@Aspect
@Component
public class LoggingAspect {

  @Resource
  private LogMapper logMapper;

  @Around("@annotation(tLog)")
  public Object TLog(ProceedingJoinPoint joinPoint, TLog tLog) throws Throwable{
    long start = System.currentTimeMillis();
//  执行目标方法
    Object proceed = joinPoint.proceed();
    long executionTime = System.currentTimeMillis() - start;
    //  存入日志表
//  默认本地用户
    Log log = new Log(
            0L,
            "local",
            tLog.request(),
            ((MethodSignature)joinPoint.getSignature()).getMethod().getName(),
            InetAddress.getLocalHost().getHostAddress(),
            executionTime
    );
    int i = logMapper.insertLog(log);
    if(0 == i){
      throw new RuntimeException("日志添加失败!");
    }
    System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
    return proceed;
  }

}
